package captcha

import (
	"fmt"
	"github.com/astaxie/beego/httplib"
	"time"
)

const appId = "2037760096"
const secretKey = "0PrQK2e8kPwm47VC0JFeM5w**"

type Captcha struct {
	Response  string
	EvilLevel string
	ErrMsg    string
}

/*
	@name 验证
	@param ticket	string	票据
	@param randstr	string	随机串
	@param userip	string	用户Ip
	@return			bool	验证状态
*/
func Verify(ticket, randstr, userip string) bool {
	url := "https://ssl.captcha.qq.com/ticket/verify?aid=" + appId + "&AppSecretKey=" + secretKey + "&Ticket=" + ticket + "&Randstr=" + randstr + "&UserIP=" + userip
	if err := httpGet(url); err == nil {
		return true
	}
	return false
}
func httpGet(url string) error {
	b := httplib.Get(url)
	b.SetTimeout(60*time.Second, 30*time.Second)
	b.Header("Accept-Encoding", "gzip,deflate,sdch")
	b.Header("Host", "cloud.oj-time.cn")
	b.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36")
	b.Header("Content-Type", "application/json")
	_, err := b.Response()

	var resp Captcha
	if err == nil {
		err = b.ToJSON(&resp)
		fmt.Println("Response：", resp, err)
		if err != nil {
			return err
		}
		if resp.Response == "1" {
			return nil
		}
	}
	return err
}
